package com.mazaiting.gateway.util;

import com.alibaba.fastjson.JSON;
import com.mazaiting.common.core.domain.result.Result;
import com.mazaiting.common.core.domain.result.ResultCode;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 异常响应工具类
 */
public class WebFluxUtil {

    /**
     * 写入异常信息
     * @param response 响应
     * @param resultCode 结果码
     * @return 空
     */
    public static Mono<Void> writeErrorInfo(ServerHttpResponse response, ResultCode resultCode) {
        switch (resultCode) {
            case TOKEN_INVALID_OR_EXPIRED -> response.setStatusCode(HttpStatus.UNAUTHORIZED);
            case ACCESS_UNAUTHORIZED, TOKEN_ACCESS_FORBIDDEN -> response.setStatusCode(HttpStatus.FORBIDDEN);
            default -> response.setStatusCode(HttpStatus.BAD_REQUEST);
        }
        // 设置相应头
        HttpHeaders headers = response.getHeaders();
        // 设置编码
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());
        // 设置内容类型
        headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        // 设置跨域
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        // 设置无缓存
        headers.set(HttpHeaders.CACHE_CONTROL, "no-cache");
        // 返回相应
        String body = JSON.toJSONString(Result.failed(resultCode));
        // 设置内容
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer)).doOnError(error -> DataBufferUtils.release(buffer));
    }

}
